<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>固定资产管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="pageContentWhole">
      <a-row :gutter="[16]">
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="资产名称">
              <a-input v-model="searchForm.name"></a-input>
            </a-form-item>
            <a-form-item label="资产类型">
              <a-select v-model="searchForm.type" class="selectWidth" >
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in types" :key="v.key">{{v.title}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="所属公司">
              <a-tree-select class="selectWidth"
                v-model="searchForm.deptId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="deptTreeData"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item label="购入日期">
              <a-range-picker @change="onChange"><a-icon slot="suffixIcon" type="calendar" /></a-range-picker>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="addItem">+  添加固定资产</a-button>
            </a-form-item>
          </a-form>

          <a-card style="text-align:center; margin-top:24px;">
            <a-col :span="12" class="assent">
              <div class="assent_mes">固定资产数量</div>
              <div class="assent_shu">{{capitalFixedStatistics.capitalCount||'--'}}</div>
            </a-col>
            <a-col :span="12">
              <div class="assent_mes">固定资产总价值</div>
              <div class="assent_shu">{{capitalFixedStatistics.totalValue||'--'}}</div>
            </a-col>
          </a-card>

          <a-table :columns="columns" :data-source="tableData" :loading="loading" class="tableMargin" :pagination="pagination" rowKey="id">
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="operation" slot-scope="text, record">
                <a @click="editIt(record)">编辑</a>
                <a @click="deleteIt(record.id)">删除</a>
              </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 添加/编辑 -->
    <a-modal :visible="visible" :title="title" :confirmLoading="confirmLoading"
      :destroyOnClose="true" :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      >
      <a-form-model
        ref="rulesForm"
        :model="form" :label-col="labelCol" :wrapper-col="wrapperCol"
        :rules="rules">
        <a-form-model-item label="资产类型" prop="type">
          <a-select v-model="form.type" class="selectWidth" >
            <a-select-option key>请选择</a-select-option>
            <a-select-option v-for="v in types" :key="v.key">{{v.title}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="资产名称" prop="name">
          <a-input v-model="form.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="所属公司" prop="deptId">
          <a-tree-select placeholder="请选择公司" :treeDefaultExpandAll="treeDefaultExpandAll"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="deptTreeDataModal"
          >
          </a-tree-select>
        </a-form-model-item>
        <!-- 1.1修改字段和添加字段 -->
        <a-form-model-item label="购入日期" prop="purchaseDate">
          <a-date-picker v-model="form.purchaseDate"><a-icon slot="suffixIcon" type="calendar" /></a-date-picker>
        </a-form-model-item>
        <a-form-model-item label="资产含税价值（元）" prop="value">
          <a-input-number v-model="form.value" :min="0" :precision="2" :max="999999999999.99" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="税金（元）" prop="taxes">
          <a-input-number v-model="form.taxes" :min="0" :precision="2" :max="999999999999.99" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="税率（%）" prop="taxRate">
          <a-input-number v-model="form.taxRate" :min="0" :precision="2" style="width: 100%"></a-input-number>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { queryDeptList } from '@/api/systemPersonnelManage'
import {queryCompanyCapitalFixed, addCompanyCapitalFixed, updateCompanyCapitalFixed, deleteCompanyCapitalFixed} from '@/api/financialCenter'

const fomrMessage = `必填项不能为空`
const types = [
  {key: 'SHIP', title: '船舶'},
  {key: 'TRACTOR', title: '牵引车'},
  {key: 'TRAILER', title: '挂车'},
  {key: 'CAR', title: '公司轿车'},
  {key: 'OTHER', title: '其它'}
]
const defaultForm = () => {
  return {
    id: null,
    name: '', // 定资产名称
    type: '', // 产类型
    deptId: '', // 构id
    purchaseDate: null, // 入日期
    value: null,
    taxRate: null,
    taxes: null
  }
}

export default {
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        scopedSlots: {customRender: 'rn'}
      },
      {
        title: '资产类型',
        dataIndex: 'type',
        customRender: (text, row, index) => {
          let t = this.types.filter(v => v.key === text)[0]
          if (t) return t.title
          return text
        }
      },
      {
        title: '资产名称',
        dataIndex: 'name',
        ellipsis: true
      },
      {
        title: '所属公司',
        dataIndex: 'companyName',
        ellipsis: true
      },
      {
        title: '购入日期',
        dataIndex: 'purchaseDate'
      },
      {
        title: '含税价值（元）',
        dataIndex: 'value',
        width: 150
      },
      {
        title: '税金（元）',
        dataIndex: 'taxes'
      },
      {
        title: '税率',
        dataIndex: 'taxRate',
        customRender: (text, row, index) => {
          return `${text}%`
        }
      },
      {
        title: '操作',
        width: 160,
        scopedSlots: {customRender: 'operation'}
      }
    ]

    return {
      deptTreeData: [],
      deptTreeDataModal: [],
      types,
      searchForm: {
        name: '',
        type: '', // 资产类型
        deptId: '', // 架构id
        searchStartTime: '',
        searchEndTime: ''
      },
      columns,
      tableData: [],
      capitalFixedStatistics: {},
      loading: false,
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // modal
      labelCol: {span: 8},
      wrapperCol: {span: 14},
      visible: false,
      title: '',
      confirmLoading: false,
      form: defaultForm(),
      rules: {
        deptId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        name: [{required: true, message: fomrMessage, trigger: 'blur'}],
        type: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        value: [{required: true, message: fomrMessage, trigger: 'blur'}],
        taxes: [{required: true, message: fomrMessage, trigger: 'blur'}],
        taxRate: [{required: true, message: fomrMessage, trigger: 'blur'}],
        purchaseDate: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}]
      },
      treeDefaultExpandAll: false
    }
  },
  methods: {
    onChange (data, dateString) {
      this.searchForm.searchStartTime = dateString[0]
      this.searchForm.searchEndTime = dateString[1]
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      queryCompanyCapitalFixed({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.companyCapitalFixedList.list
        this.capitalFixedStatistics = rsp.data.capitalFixedStatistics
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.companyCapitalFixedList.pageSize,
          total: rsp.data.companyCapitalFixedList.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.companyCapitalFixedList.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      }).catch(() => { this.loading = false })
    },
    // 添加
    addItem () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = defaultForm()
      this.title = '创建固定资产'
      this.treeDefaultExpandAll = false
      this.visible = true
    },
    // 编辑
    editIt (item) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = {...item}
      this.title = '编辑固定资产'
      this.treeDefaultExpandAll = true
      this.visible = true
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const data = Object.assign({}, this.form, {purchaseDate: this.form.purchaseDate.format ? this.form.purchaseDate.format('YYYY-MM-DD') : this.form.purchaseDate})
          if (!this.form.id) {
            addCompanyCapitalFixed(data).then(rsp => {
              this.$message.success('添加成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          } else {
            updateCompanyCapitalFixed(data).then(rsp => {
              this.$message.success('编辑成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    deleteIt (id) {
      if (!this.$root._bc.drop) {
        this.$message.error('您无此权限！')
        return
      }
      const _t = this
      this.$confirm({
        title: '删除交易记录后将影响金额统计，确认删除？',
        onOk () {
          deleteCompanyCapitalFixed({id}).then(rsp => {
            _t.$message.success('删除成功')
            _t.handleSubmit()
          })
        }
      })
    }
  },
  mounted () {
    queryDeptList({parentId: 0}).then(rsp => {
      let initData = [{
        title: '全部',
        key: '',
        value: '',
        isLeaf: true
      }]
      const p = rsp.data[0]
      queryDeptList({parentId: p.deptId}).then(rsp => {
        let childrenData = []
        rsp.data.forEach((value) => {
          childrenData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId,
            isLeaf: true
          })
        })
        initData.push({
          title: p.name,
          key: p.deptId,
          value: p.deptId,
          children: childrenData
        })
        this.deptTreeData = [...initData]
        this.deptTreeDataModal = [...initData]
        this.searchForm.deptId = this.deptTreeData[0].key
        this.handleSubmit()

        // 弹窗的
        initData.splice(0, 1, {
          title: '请选择',
          key: '',
          value: '',
          isLeaf: true
        })
        this.deptTreeDataModal = [...initData]
      })
    })
  }
}
</script>

<style lang="less" scoped>
</style>
